<?php
namespace Trawind\NetSuite\Repository\Account\Account;

use Trawind\NetSuite\PHPToolkit\AddRequest;
use Trawind\NetSuite\PHPToolkit\UpdateRequest;
use Trawind\NetSuite\PHPToolkit\RecordRef;
use Trawind\NetSuite\PHPToolkit\InventoryItem;
use Trawind\NetSuite\Repository\Common;
use Trawind\NetSuite\PHPToolkit\SubsidiarySearchBasic;

class Subsidiary extends Common
{
    public $service;

    public $type = 'subsidiary';

    public $pageSize = 1000;
    
    public $search = SubsidiarySearchBasic::class;

    public $searchFields = ['internalId', 'name'];

    public function __construct($config=null)
    {
        parent::__construct($config);
    }

    /**
     * @param $data
     * @return mixed
     * @throws \Exception
     */
    public function store($data)
    {
        $sku = $data;

        $inventoryItemer = new InventoryItem();
        $inventoryItemer->itemId = $sku['name'];

        $inventoryItemer->taxSchedule = new RecordRef();
        $inventoryItemer->taxSchedule->internalId = 1;
        $request = new AddRequest();
        $request->record = $inventoryItemer;
        $response = $this->service->add($request);
        if (!$response->writeResponse->status->isSuccess) {
            throw new \Exception($response->writeResponse->status->statusDetail[0]->message);
        }
        return $response->writeResponse->baseRef->internalId;
    }

    /**
     * @param $id
     * @param $data
     * @return mixed
     * @throws \Exception
     */
    public function update($id, $data)
    {
        $sku = $data;
        $this->service = $this->connect();
        $inventoryItemer = $this->show($id);
        $inventoryItemer->itemId = $sku['name'];

        $request = new UpdateRequest();
        $request->record = $inventoryItemer;

        $this->service->setPreferences(false, false, false, true);

        $response = $this->service->update($request);
        if (!$response->writeResponse->status->isSuccess) {
            throw new \Exception($response->writeResponse->status->statusDetail[0]->message);
        }
        return $response->writeResponse->baseRef->internalId;
    }
}


